#!/usr/bin/python

import calendar
import time
from datetime import date
from string import Template
from docutils.core import publish_parts

def main():
    """
    This is the main function that decides the script and calls the date calculating function.
    """
    DAY_DICT = {0: "Monday",1: "Tuesday",2: "Wednesday",3: "Thursday",4: "Friday",5: "Saturday",6: "Sunday"}
    venue = "Department of Astronomy,<br />Osmania University<br />"
    meet_time = "2:00 PM"

    y,m,d = calc_meet_date(int(time.strftime('%Y')),int(time.strftime('%m')))

    if date.today() > date(y,m,d):
        y,m,d = calc_meet_date(None,m+1)

    try:
        f = open("/home/ilughyd/agendas/agenda_%d%d%d.txt" %(y,m,d),"r")
        agenda = publish_parts(unicode(f.read()),writer_name="html4css1")['html_body']
        f.close()
    except IOError:
        agenda = "Not set yet."

    day_of_meet = DAY_DICT[calendar.weekday(y,m,d)]
    m_name = date(y,m,d).strftime('%B')

    f = open("/home/ilughyd/scripts/base.html","r")
    file_contents = f.read()
    f.close()

    date_sub_template = Template(file_contents)

    modified_contents = date_sub_template.safe_substitute({'m_date':d,'m_month':m_name,'m_weekday': day_of_meet,'m_year':y,'venue':venue,'m_time':meet_time,'meet_agenda':agenda,})

    f = open("/home/ilughyd/public_html/index.html","w")
    f.write(modified_contents)
    f.close()

    return 0

def calc_meet_date(year=None,month=None):
    """
    This function calculates the date of the meet.
    """
    if year:
        if month:
            month_cal = calendar.monthcalendar(year,month)

            sunday_list = [ day[6] for day in month_cal if day[6] ]

            date_of_meet = sunday_list[-1]
            month_of_meet = month
            year_of_meet = year
        else:
            month = int(time.strftime('%m'))
    else:
        if month > 12:
            year = int(time.strftime('%Y')) + 1
            month = 1
        else:
            year = int(time.strftime('%Y'))

        year_of_meet, month_of_meet, date_of_meet = calc_meet_date(year,month)

    return year_of_meet, month_of_meet, date_of_meet


if __name__ == '__main__':
    main()
